function getParameterByName(name, url) {
    url = url || window.location.href;
    name = name.replace(/[\[\]]/g, '\\$&');
    var regex = new RegExp('[?&]' + name + '(=([^&#]*)|&|#|$)'),
        results = regex.exec(url);
    if (!results) return null;
    if (!results[2]) return '';
    return decodeURIComponent(results[2].replace(/\+/g, ' '));
}

const urlParams = new URLSearchParams(window.location.search);
const root = urlParams.get('uroot');

var uroot = getParameterByName('uroot');

var uid = getParameterByName('uid');
const id = parseInt(uid, 10);

var name = getParameterByName('uname');

function aaa() {
    window.location.href = "main.html?uroot=" + encodeURIComponent(uroot) + "&uid=" + encodeURIComponent(id) + "&uname=" + encodeURIComponent(name)
}

function bbb() {
    window.location.href = "manage.html?uroot=" + encodeURIComponent(uroot) + "&uid=" + encodeURIComponent(id) + "&uname=" + encodeURIComponent(name)
}

// 定义配置
const config = {
    apis: {
        color: '/countColor', // 车辆颜色占比的 API
        trend: '/countMonthlySales', // 月度销售趋势的 API
        brand: '/countBrandRatio', // 各品牌销售占比的 API
        priceRange: '/countPriceRange',// 价格区间分布的 API
        stock: '/sselectcarall', // 新增库存接口
        sold: '/unselectcarall' // 售出车辆接口
    },
    refreshInterval: 10000000 // 刷新间隔，单位毫秒
};

// Dashboard类
class Dashboard {
    constructor() {
        this.scrollAnimations = new Map(); // 改用Map管理多个滚动器
        this.scrollInterval = null; // 滚动定时器
        this.scrollStep = 1; // 滚动步长
        this.charts = {
            coverage: null, // 车辆颜色占比图表
            trend: null, // 月度销售趋势图表
            brand: null, // 各品牌销售占比图表
            priceRange: null // 价格区间分布图表
        };
        this.init();
    }

    async init() {
        await this.loadData();
        this.bindEvents();
        setInterval(() => this.loadData(), config.refreshInterval);
    }

    async loadData() {
        try {
            const colorData = await this.fetchData(config.apis.color);
            const trendData = await this.fetchData(config.apis.trend);
            const brandData = await this.fetchData(config.apis.brand);
            const priceRangeData = await this.fetchData(config.apis.priceRange);
            const stockData = await this.fetchData(config.apis.stock);
            const soldData = await this.fetchData(config.apis.sold);
            this.updateSoldList(soldData);
            this.updateStockList(stockData); // 新增库存数据处理
            this.updateCharts({colorData, trendData, brandData, priceRangeData});
        } catch (error) {
            console.error('数据加载失败:', error);
        }
    }

    // 售出车辆列表更新方法
    updateSoldList(data) {
        const container = document.querySelector('.main_bottom_t_l_main2 ul');
        if (!container) return;

        container.innerHTML = data.map(car => `
        <li class="scroll-item">
            <div class="main_bottom_t_l_main_list">
                <div class="main_bottom_t_list_title">
                    <span class="car-name">${car.cid}</span> <!-- 新增字段 -->
                    <span class="car-name">${car.cname}</span>
                    <span class="car-info">${car.color} | ${(car.price / 10000).toFixed(1)}万</span>
                    <span class="car-time">${car.time}</span>
                    <span class="car-time">${car.storage}</span> <!-- 新增字段 -->
                </div>
            </div>
        </li>
    `).join('');

        // 启动自动滚动
        this.autoScroll(
            document.querySelector('.main_bottom_t_l_con:has(.main_bottom_t_l_main2)'),
            'ul'
        );
    }

    autoScroll(container, listSelector) {
        // 清理旧动画
        if (this.scrollAnimations.has(container)) {
            cancelAnimationFrame(this.scrollAnimations.get(container));
        }

        const list = container.querySelector(listSelector);
        if (!list.children.length) return;

        let startTime = null;
        const itemHeight = list.firstElementChild.offsetHeight;
        const containerHeight = container.offsetHeight;
        const totalItems = list.children.length;
        const duration = totalItems * 2000; // 根据条目数动态计算时长

        const animate = (timestamp) => {
            if (!startTime) startTime = timestamp;
            const progress = timestamp - startTime;

            // 计算当前滚动位置
            const scrollPos = (progress / duration) * (totalItems * itemHeight);

            // 应用平滑滚动
            list.style.transform = `translateY(-${scrollPos % (totalItems * itemHeight)}px)`;

            // 循环动画
            this.scrollAnimations.set(container, requestAnimationFrame(animate));
        };
        // 仅在内容超出时启动
        if (totalItems * itemHeight > containerHeight) {
            this.scrollAnimations.set(container, requestAnimationFrame(animate));
        }
    }

    // 新增库存列表更新方法
    updateStockList(data) {
        const container = document.querySelector('.main_bottom_t_l_main ul');
        if (!container) {
            console.error('库存容器元素不存在');
            return;
        }

        // 清空现有内容
        container.innerHTML = '';

        // 创建新列表项
        data.forEach(car => {
            const li = document.createElement('li');
            li.className = 'scroll-item';
            li.innerHTML = `
            <div class="main_bottom_t_l_main_list">
                <div class="main_bottom_t_list_title">
                    <span class="car-name">${car.cid}</span> <!-- 新增字段 -->
                    <span class="car-name">${car.cname}</span>
                    <span class="car-info">${car.color} | ${(car.price / 10000).toFixed(1)}万</span>
                    <span class="car-time">${car.time}</span>
                    <span class="car-time">${car.storage}</span> <!-- 新增字段 -->
                </div>
            </div>
        `;
            container.appendChild(li);
        });

        this.autoScroll(
            document.querySelector('.main_bottom_t_l_con:has(.main_bottom_t_l_main)'),
            'ul'
        );
    }

    async fetchData(url) {
        const res = await fetch(url);
        return res.json();
    }

    updateCharts(data) {
        // 更新车辆颜色占比图表
        this.updateCoverageChart(data.colorData);
        // 更新月度销售趋势图表
        this.updateTrendChart(data.trendData);
        // 更新各品牌销售占比图表
        this.updateBrandChart(data.brandData);
        // 更新价格区间分布图表
        this.updatePriceRangeChart(data.priceRangeData);
    }

    updateCoverageChart(data) {
        // 确保 DOM 元素存在
        const coverageDom = document.getElementById('coverageId');
        if (!coverageDom) {
            console.error('DOM 元素不存在: coverageId');
            return;
        }

        // 初始化 ECharts 实例
        if (!this.charts.coverage) {
            this.charts.coverage = echarts.init(coverageDom);
        }

        // 设置图表配置
        this.charts.coverage.setOption(this.getCoverageOption(data));
    }

    getCoverageOption(data) {
        // 创建颜色映射表，将汉字颜色映射到实际的颜色值
        const colorMapping = {
            '红': '#FFB6C1',
            '蓝': '#ADD8E6',
            '绿': '#00FF00',
            '黄': '#FFFF00',
            '黑': '#000000',
            '白': '#FFFFFF',
            '灰': '#CCCCCC',
            '紫': '#800080',
            '粉': '#FFC0CB',
            '橙': '#FFA500'
        };

        return {
            tooltip: {
                trigger: 'item',
                formatter: ({name, value, percent}) => `
                <div style="font-weight:500; font-size: 14px;">${name}</div>
                <div>数量：${value}辆</div>
                <div>占比：${percent}%</div>
            `,
                textStyle: {
                    fontSize: 14
                }
            },
            legend: {
                show: false
            },
            series: [{
                type: 'pie',
                radius: ['40%', '70%'],  // 调整半径范围
                center: ['50%', '50%'],
                avoidLabelOverlap: false,
                label: {
                    show: true,
                    position: 'outer',
                    formatter: '{b}: {d}%',
                    fontSize: 14,  // 增大标签字体
                    color: '#fff'
                },
                labelLine: {
                    show: true,
                    length: 10,
                    length2: 20
                },
                data: data.map(d => ({
                    name: d.color,
                    value: d.count,
                    itemStyle: {
                        color: colorMapping[d.color] || '#CCCCCC'  // 使用映射表中的颜色，若不存在则使用灰色
                    }
                }))
            }]
        };
    }


    updateTrendChart(data) {
        // 确保 DOM 元素存在
        const trendDom = document.getElementById('contentId');
        if (!trendDom) {
            console.error('DOM 元素不存在: contentId');
            return;
        }

        // 初始化 ECharts 实例
        if (!this.charts.trend) {
            this.charts.trend = echarts.init(trendDom);
        }

        // 设置图表配置
        this.charts.trend.setOption(this.getTrendOption(data));
    }

    getTrendOption(data) {
        return {
            xAxis: {
                type: 'category',
                data: data.map(d => d.month),
                axisLabel: {
                    rotate: 45,
                    color: '#FFFFFF'
                }
            },
            yAxis: {
                name: '销售数量',
                type: 'value',
                axisLabel: {
                    color: '#FFFFFF'
                }
            },
            series: [{
                type: 'line',
                data: data.map(d => d.sales),
                label: {
                    show: true,
                    position: 'top',
                    formatter: '{@[1]}辆',
                    color: '#FFFFFF'
                },
                itemStyle: {
                    color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
                        {offset: 0, color: '#54D3FF'},
                        {offset: 1, color: '#193c8f'}
                    ])
                }
            }]
        };
    }

    updateBrandChart(data) {
        // 确保 DOM 元素存在
        const brandDom = document.getElementById('publicNumId');
        if (!brandDom) {
            console.error('DOM 元素不存在: publicNumId');
            return;
        }

        // 初始化 ECharts 实例
        if (!this.charts.brand) {
            this.charts.brand = echarts.init(brandDom);
        }

        // 设置图表配置
        this.charts.brand.setOption(this.getBrandOption(data));
    }


    getBrandOption(data) {
        const total = data.reduce((sum, d) => sum + d.total, 0); // 计算总数量
        return {
            tooltip: {
                trigger: 'axis',
                axisPointer: {
                    type: 'shadow'
                },
                formatter: function (params) {
                    let result = params[0].name + '<br/>';
                    params.forEach(function (param) {
                        result += param.marker + param.seriesName + ': ' + param.value + param.unit + '<br/>';
                    });
                    return result;
                }
            },
            legend: {
                show: false // 隐藏图例
            },
            grid: {
                left: '3%',
                right: '4%',
                bottom: '3%',
                containLabel: true
            },
            xAxis: {
                type: 'category',
                data: data.map(d => d.brand),
                axisLabel: {
                    color: '#FFFFFF'
                }
            },
            yAxis: [
                {
                    type: 'value',
                    name: '销售数量',
                    axisLabel: {
                        color: '#FFFFFF'
                    }
                },
                {
                    type: 'value',
                    name: '销售占比',
                    position: 'right',
                    axisLabel: {
                        formatter: '{value}%',
                        color: '#FFFFFF'
                    }
                }],
            series: [
                {
                    name: '销售数量',
                    type: 'bar',
                    data: data.map(d => d.sold),
                    itemStyle: {
                        color: '#5470c6'
                    },
                    label: {
                        show: true,
                        position: 'top',
                        formatter: '{c}辆',
                        color: '#FFFFFF'
                    }
                },
                {
                    name: '销售占比',
                    type: 'line',
                    yAxisIndex: 1,
                    data: data.map(d => d.ratio),
                    itemStyle: {
                        color: '#ff7300'
                    },
                    label: {
                        show: true,
                        position: 'top',
                        formatter: '{c}%',
                        color: '#FFFFFF'
                    }
                }]
        };
    }


    updatePriceRangeChart(data) {
        // 确保 DOM 元素存在
        const priceRangeDom = document.getElementById('yearsNumId');
        if (!priceRangeDom) {
            console.error('DOM 元素不存在: yearsNumId');
            return;
        }

        // 初始化 ECharts 实例
        if (!this.charts.priceRange) {
            this.charts.priceRange = echarts.init(priceRangeDom);
        }

        // 设置图表配置
        this.charts.priceRange.setOption(this.getPriceRangeOption(data));
    }

    getPriceRangeOption(data) {
        console.log('PriceRange Data:', data);
        const sortedData = [...data].sort((a, b) =>
            parseInt(a.price_range) - parseInt(b.price_range)
        );
        return {
            tooltip: {
                trigger: 'axis',
                formatter: function (params) {
                    return `价格区间: ${params[0].name}<br/>数量: ${params[0].value}`;
                }
            },
            grid: {
                left: '1%',
                right: '7%',
                bottom: '12%',
                containLabel: true
            },
            xAxis: {
                type: 'value',
                axisLabel: {
                    color: '#FFFFFF',
                    formatter: '{value} 辆'
                },
                splitLine: {
                    lineStyle: {
                        color: 'rgba(255,255,255,0.2)'
                    }
                }
            },
            yAxis: {
                type: 'category',
                data: sortedData.map(d => {
                    const range = d.price_range?.replace('', '') || '';
                    return `${range}`; //
                }),
                axisLabel: {
                    color: '#FFFFFF',
                    fontSize: 10,
                    rotate: 45, // 价格区间较长时旋转标
                    margin: 12,
                    formatter: value =>
                        value.replace('', '')
                }
            },
            axisTick: {
                lineStyle: {
                    color: 'rgba(255,255,255,0.6)'
                }
            },

            series: [{
                type: 'bar',
                data: sortedData.map(d => d.count),
                itemStyle: {
                    color: new echarts.graphic.LinearGradient(1, 0, 0, 0, [
                        {offset: 0, color: '#37D2D4'},
                        {offset: 1, color: '#2E8CFF'}
                    ]),
                    borderRadius: [0, 8, 8, 0]
                },
                barWidth: '70%',  // 控制柱子宽度
                label: {
                    show: true,
                    position: 'right',
                    color: '#FFFFFF',
                    fontSize: 10,
                    formatter: '{@[1]}'
                }
            }]
        };
    }

    // 添加窗口resize处理
    bindEvents() {
        window.addEventListener('resize', () => {
            this.scrollAnimations.forEach((_, container) => {
                cancelAnimationFrame(this.scrollAnimations.get(container));
                this.autoScroll(container, 'ul'); // 重新初始化滚动
            });
        });
    }
}

// 初始化看板
document.addEventListener('DOMContentLoaded', () => {
    new Dashboard();
});

// 更新日期、星期和时间
function updateDateTime() {
    const now = new Date();

    // 更新日期
    const dateOptions = {year: 'numeric', month: 'long', day: 'numeric'};
    document.getElementById('currentDate').textContent = now.toLocaleDateString('zh-CN', dateOptions);

    // 更新星期
    const days = ['日', '一', '二', '三', '四', '五', '六'];
    document.getElementById('currentDay').textContent = `星期${days[now.getDay()]}`;

    // 更新时间
    const timeOptions = {hour: '2-digit', minute: '2-digit', second: '2-digit'};
    document.getElementById('currentTime').textContent = now.toLocaleTimeString('zh-CN', timeOptions);
}

// 初始化日期时间
updateDateTime();

// 每秒更新时间
setInterval(updateDateTime, 1000);
